﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.Script
{
    /// <summary>
    /// 用于供脚本访问组件的类
    /// </summary>
    public class PartScriptObject
    {
        private WeakReference _part;
        public PartScriptObject(Part part)
        {
            _part = new WeakReference(part);
        }

        /// <summary>
        /// 设置组件的属性值
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        public void setPropertyXmlString(string propertyName, object value)
        {
            Part part = _part.Target as Part;
            if (part != null)
            {
                XProperty.XPropertyDescription description = XPropertyUtility.GetXPropertyDescription(part, propertyName);
                if (description != null)
                {
                    XProperty.Converters.ConvertContext context = new XProperty.Converters.ConvertContext();
                    Coolzon.Metadata.ValueNode valueNode = Coolzon.Metadata.ValueNode.Parse(Convert.ToString(value));
                    XPropertyUtility.SetXPropertyValue(context, part, description, valueNode);
                }
            }
        }

        /// <summary>
        /// 获取组件的属性值
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public object getPropertyXmlString(string propertyName)
        {
            Part part = _part.Target as Part;
            if (part != null)
            {
                XProperty.XPropertyDescription description = XPropertyUtility.GetXPropertyDescription(part, propertyName);
                if (description != null)
                {
                    XProperty.Converters.ConvertContext context = new XProperty.Converters.ConvertContext();
                    return XPropertyUtility.GetXPropertyValue(context, part, description);
                }
            }
            return null;
        }
    }
}
